using UnityEngine;
using System.Collections;

public class Anim : MonoBehaviour {
	
	public int nbSprite;
	public float speed;
	
	public int index;
	public float timer;
	public bool reverse;
    public bool loop;
	
	// Use this for initialization
	void Start () {
		this.renderer.material.mainTextureScale = new Vector2(1/(float)nbSprite, 0.99f);
		timer = speed;
		index = 0;

        loop = true;
		if(reverse)
			index = nbSprite -1;
	}
	
	// Update is called once per frame
	void Update () {
		
		if(speed == -1)
			return;
		
		timer -= Time.deltaTime;
		
		if(timer < 0){
			if(!reverse)
				index ++;
			else
				index --;
			
			if(index >= nbSprite || index < 0){

                if (!loop)
                    return;

				index = 0;
				
				if(reverse)
					index = nbSprite -1;
			}
			this.renderer.material.mainTextureOffset = new Vector2(index / (float)nbSprite, 0);
			
			timer = speed;
		}
		
	}
	
	public void resetTimer(Texture texture, int nb){
		
		timer = speed;
		nbSprite = nb;
		this.renderer.material.mainTextureScale = new Vector2(1/(float)nbSprite, 0.99f);
		this.renderer.material.mainTextureOffset = new Vector2(index / (float)nbSprite, 0);
		this.renderer.material.SetTexture("_MainTex", texture);
	}
	
    public void Apply()
    {
        timer = speed;
        index = 0;
        this.renderer.material.mainTextureScale = new Vector2(1 / (float)nbSprite, 0.99f);
        this.renderer.material.mainTextureOffset = new Vector2(index / (float)nbSprite, 0);
    }

	public void changeIndex(int num){
		index = num;
		this.renderer.material.mainTextureOffset = new Vector2(num / (float)nbSprite, 0);
		
	}
}
